package com.gouldzd.controller;

import com.gouldzd.constant.MessageConstant;
import com.gouldzd.entity.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/*
 * @Author zhangdan
 * @Description //TODO 用户操作管理
 * @Date 9:56 2020/4/28
 * @Param 
 * @return 
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    //获取当前用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){
        //当spring security完成认证后,会将当前用户信息保存到框架提供的上下文对象(还可使用Session获取用户名)
        User user= (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //String username = SecurityContextHolder.getContext().getAuthentication().getName();//或者直接获取用户名

        System.out.println("当前用户:"+user);

        //判断用户是否为空
        if(user != null){
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }
        return new Result(false,MessageConstant.GET_USERNAME_FAIL);
    }
}
